
package org.sopt.dev.ImgKnight.monitor.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.LinkedList;
import java.util.List;

import org.sopt.dev.ImgKnight.monitor.Monitor;
import org.sopt.dev.ImgKnight.monitor.dialog.AlertDialog;


public class HarvestDAO {
	
	Monitor monitor = null;
	
	String ip = null;
	
	String port = null;
	
	String id = null;
	
	String passwd = null;
	
	public HarvestDAO(Monitor monitor, String ip, String port, String id, String passwd) {
		this.monitor = monitor;
		this.ip = ip;
		this.port = port;
		this.id = id;
		this.passwd = passwd;
	}
	
	public List<HarvestVO> getRecentLog(int size) {
		List<HarvestVO> recentLog = new LinkedList<HarvestVO>();
		if( size <= 0 )
			size = 1000;
		Connection conn = null;
		PreparedStatement stat = null;
		ResultSet rs = null;
		try {
			conn = getConnection();
			if( conn != null ) {
				stat = conn.prepareStatement("select * from harvest order by id desc limit ?");
				stat.setInt(1, size);
				rs = stat.executeQuery();
				if( rs != null ) {
					
					while( rs.next() ) {
						HarvestVO vo = new HarvestVO();
						vo.setId(rs.getString("id"));
						vo.setSite(rs.getString("site"));
						vo.setPageUrl(rs.getString("page_url"));
						vo.setImgUrl(rs.getString("image_url"));
						vo.setFileName(rs.getString("filename"));
						vo.setSize(rs.getString("size"));
						vo.setStatus(rs.getString("status"));
						vo.setCountryCode(rs.getString("countryCode"));
						vo.setCountryName(rs.getString("countryName"));
						vo.setTimestamp(rs.getString("timestamp"));
						recentLog.add(vo);
					}
				}
			}
		} catch (Exception e) {
			AlertDialog.alert(monitor.getShell(), "Execute Error", e.getMessage());
		} finally {
			if( rs != null ) try{ rs.close(); } catch(Exception e){}
			if( stat != null ) try{ stat.close(); } catch(Exception e){}
			if( conn != null ) try{ conn.close(); } catch(Exception e){}
		}
		return recentLog;
	}
	
	private Connection getConnection() {
		Connection conn = null;
		try {
			Class.forName("com.mysql.jdbc.Driver");
			conn = DriverManager.getConnection(
					"jdbc:mysql://"+ip+":"+port+"/dspider", id, passwd);
		} catch (Exception e) { 
			AlertDialog.alert(monitor.getShell(), "Execute Error", e.getMessage());
		}
		return conn;
	}
	
}
